package com.srb.aliyun.oss.controller.api;

import com.srb.aliyun.oss.service.FileService;
import com.srb.common.exception.BusinessException;
import com.srb.common.result.R;
import com.srb.common.result.ResponseEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Api(tags = {"阿里云文件管理"})
//@CrossOrigin
@RestController
@RequestMapping(value = {"/api/oss/file"})
public class FileController {

    @Autowired
    private FileService fileService;

    @ApiOperation (value = "上传文件到阿里云")
    @PostMapping(value = {"/upload"})
    public R upload(
            @ApiParam(value = "文件",required = true)
            @RequestParam(value = "file") MultipartFile file,
            @ApiParam(value = "模块",required = true)
            @RequestParam(value = "module") String module){
        try {
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();
            String url = fileService.uploadToAliyun(inputStream, module, filename);
            return R.ok().message("文件上传成功").data("url",url);
        } catch (IOException e) {
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR,e);
        }
    }

    @ApiOperation (value = "删除阿里云文件")
    @DeleteMapping(value = {"/remove"})
    public R remove(
            @ApiParam(value = "要删除的文件地址",required = true)
            @RequestParam(value = "url") String url){
        fileService.removeFile(url);
        return R.ok().message("删除成功");
    }
}
